package com.sheeran.aichat.dto.common.rest;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.sheeran.aichat.exception.BusinessException;
import com.sheeran.aichat.utils.rest.ResponseCode;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * @author: sheeran
 * @create: 2025/02/10
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonPropertyOrder({ "code", "msg", "timestamp", "result" })
public class WrappedResponse<T> implements Serializable {

    private static final long serialVersionUID = 6785843178757286946L;
    /**
     * 返回码
     */
    private int code;

    /**
     * 返回描述
     */
    private String msg;

    /**
     * 返回时间
     */
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
    private LocalDateTime timestamp;

    /**
     * 返回数据
     */
    private T result;

    public WrappedResponse(ResponseCode responseCode, T result) {
        this.code = responseCode.getCode();
        this.msg = responseCode.getMsg();
        this.timestamp = LocalDateTime.now();
        this.result = result;

        if (result != null && BaseOperateResponse.class.isAssignableFrom(result.getClass())) {
            // 前端需要将Reason放入到msg中
            String reason = ((BaseOperateResponse) result).getReason();
            if (StringUtils.hasText(reason)) {
                this.msg = reason;
            }
        }
    }

    public boolean isSuccess() {
        return this.code == ResponseCode.SUCCESS.getCode();
    }

    public void checkSuccess() {
        if (!isSuccess()) {
            throw new BusinessException(ResponseCode.REMOTE_CALL_ERROR, this.msg);
        }
    }
}
